import { WS, WS_CONECTION, WS_DATA, WS_LISTEN, WS_PIC_DATA, WS_SENDDATA, WS_SENDPIC } from '@/store/mutation-types'
const baseUrl = window.PROJECT_CONFIG.VUE_APP_SOCKET_API_BASE_URL
const ws = {
  state: {
    ws: null,
    wsdata: [],
    ws_pic_data: []
  },
  mutations: {
    [WS_CONECTION]: (state, ws) => {
      state[WS] = ws
    },
    [WS_DATA]: (state, data) => {
      state[WS_DATA] = data
    },
    [WS_PIC_DATA]: (state, data) => {
      state[WS_PIC_DATA] = data
    }
  },
  actions: {
    [WS_CONECTION] ({ commit, dispatch }) {
      const ws = new WebSocket(baseUrl)
      commit(WS_CONECTION, ws)
      dispatch(WS_LISTEN)
    },
    [WS_LISTEN] ({ commit, action, state }) {
      state[WS].onmessage = function(evt) {
        if (evt.data !== 'connected successfully' && evt.data) {
          commit(WS_DATA, JSON.parse(evt.data) ? JSON.parse(evt.data).realtimeData : [])
          commit(WS_PIC_DATA, JSON.parse(evt.data) ? JSON.parse(evt.data).configurationDiagramData : [])
        } else {
          commit(WS_DATA, [])
          commit(WS_PIC_DATA, [])
        }
      }
    },
    [WS_SENDDATA] ({ commit, state }, pageId) {
      if (!state[WS]) {
        return
      }
      commit(WS_DATA, [])
      state[WS].send(
        JSON.stringify({
          pageId
        })
      )
    },
    [WS_SENDPIC] ({ commit, state }, configurationDiagramIds) {
      if (!state[WS]) {
        return
      }
      commit(WS_PIC_DATA, [])
      state[WS].send(
        JSON.stringify({
          configurationDiagramIds
        })
      )
    }
  }
}

export default ws
